package cn.gistone.visualeditor.business.controller;

import cn.gistone.visualeditor.business.mapper.PictureRepository;
import cn.gistone.visualeditor.business.service.IPictureService;
import cn.gistone.visualeditor.dto.PicQueryDto;
import cn.gistone.visualeditor.entity.Picture;
import cn.gistone.visualeditor.utils.AjaxResult;
import cn.gistone.visualeditor.utils.FileUploadUtils;
import cn.gistone.visualeditor.utils.PageResult;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;

@RestController
@Api(tags = "大屏图库相关接口")
@RequestMapping("/image")
public class PictureController {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PictureRepository pictureRepository;

    @Autowired
    private IPictureService pictureService;

    @Value("${web.upload-path}")
    private String rootPath;

    @PostMapping("/upload")
    @ApiOperation(value = "图片上传接口", notes = "图片上传接口")
    public AjaxResult uploadImage(@RequestParam("file") @NotNull MultipartFile image, @NotNull Integer type) {
        String fileDir = "";
        if(type == 1){
            fileDir = "BackgroundPic";
        } else if(type == 2){
            fileDir = "SpecialEffectPic";
        }
        String path = rootPath + fileDir;
        try {
            String url = FileUploadUtils.uploadFile(image, path);
            String imageUrl =fileDir + url.substring(url.lastIndexOf(File.separator));
            Picture picture = new Picture(imageUrl,image.getOriginalFilename(), type);
            mongoTemplate.save(picture);
            return AjaxResult.ok(imageUrl);
        } catch (Exception e) {
            return AjaxResult.fail("文件上传失败");
        }
    }

    @PostMapping("/getPicPage")
    @ApiOperation("分页获取图库图片")
    public PageResult<Picture> getUserScreen(@RequestBody @Valid PicQueryDto dto){
        return pictureService.queryPage(dto);
    }

    @GetMapping("/deleteScreenById")
    @ApiOperation("根据id删除图片")
    public AjaxResult deleteScreenById(String id){
        try {
            pictureService.deleteById(id);
            return AjaxResult.ok();
        } catch (Exception e){
            return AjaxResult.fail("操作失败");
        }
    }
}
